using Domain.Entities;
using Domain.Mail;
using Domain.Permissions;
using Domain.Services;
using System;
using UserInterface.Misc;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Web;
using UserInterface.UserControls;
using System.Web.UI;
using System.IO;
using System.Configuration;

namespace UserInterface
{
    public partial class AddMessage : BoardPageBase
    {
        private Topic topic;

        protected void Page_Load(object sender, EventArgs e)
        {
            int topicId = Convert.ToInt32(Request.QueryString["topicId"]);
            topic = TopicService.GetById(topicId);
            ForumPermissionManager forumPermissionManager = PermissionManager.CreateForumPermissionManager(topic.Forum);

            if (!forumPermissionManager.Reply)
            {
                DieMessage(DieMessageType.InsufficientPermissions, "InsufficientPermissions");
            }

            string pageTitle = (string)GetLocalResourceObject("Title");
            MasterPage.TitleGenerator.PageTitle = pageTitle;
            MasterPage.TitleGenerator.ItemName = topic.Subject;
            MasterPage.HeaderText = pageTitle;
            MasterPage.AddPathItem(topic.Forum.Name, "ViewForum.aspx?forumId=" + topic.Forum.Id);
            MasterPage.AddPathItem(topic.Subject, "ViewTopic.aspx?topicId=" + topic.Id);
            MasterPage.AddPathItem(pageTitle, "AddMessage.aspx?topicId=" + topic.Id);

            PreviewMessage.Visible = false;

            if (!IsPostBack)
            {
                if (Request.QueryString["quoteMessageId"] != null)
                {
                    int quoteMessageId = Convert.ToInt32(Request.QueryString["quoteMessageId"]);
                    Message message = MessageService.GetById(quoteMessageId);
                    if (message != null)
                    {
                        ForumPermissionManager quoteMessageForumPermissionManager =
                            PermissionManager.CreateForumPermissionManager(message.Topic.Forum);
                        if (quoteMessageForumPermissionManager.Read)
                        {
                            Editor.Text = "[quote=" + message.Id + "]" + message.Text + "[/quote]";
                        }
                    }
                }

                ModeratorOptionsPlaceHolder.Visible = forumPermissionManager.Moderate;
            }
        }

        protected void AddButton_Click(object sender, EventArgs e)
        {
            string text = Editor.Text.Trim();

            if (text != "")
            {
                User user = CurrentSession.User;
                bool isForModeratorsOnly = IsForModeratorOnlyCheckBox.Checked;
                Message message = MessageService.NewMessage(topic, user, text, isForModeratorsOnly);

                string filePathFormat =
                    ConfigurationManager.AppSettings["AttachmentsDirectory"]
                    + "/"
                    + ConfigurationManager.AppSettings["AttachmentFileNameFormat"];
                MessageService.AddAttachments(
                    message,
                    Attachments.AttachmentsWithFiles,
                    filePathFormat
                );
                
                SendEmailNotifications(message);

                Response.Redirect("ViewTopic.aspx?topicId=" + topic.Id + "&messageId=" + message.Id + "#message_" + message.Id);
            }
            else
            {
                MasterPage.Messages.AddCritical(Resources.Resource.InvalidFormData);
            }
        }

        protected void PreviewButton_Click(object sender, EventArgs e)
        {
            //TODO
            //Message message = new Message();
            //message.Poster = CurrentSession.User;
            //message.PostDateTime = DateTime.Now;
            //message.Text = Editor.Text;
            //message.Attachments = Attachments.AttachmentsWithFiles;
            //PreviewMessage.Visible = true;
            //PreviewMessage.Message = message;
        }

        protected void CancelButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("ViewTopic.aspx?topicId=" + topic.Id + "&page=last");
        }

        private void SendEmailNotifications(Domain.Entities.Message message)
        {
            foreach (Bookmark bookmark in topic.Bookmarks)
            {
                MailParser mailParser = new MailParser(Server.MapPath("~/Emails/TopicEmailNotification.xml"));
                mailParser.AddSubjectTag("Subject", topic.Subject);
                mailParser.AddBodyTag("Username", bookmark.User.Username);
                mailParser.AddBodyTag("PosterUsername", message.Poster.Username);
                mailParser.AddBodyTag("MessageUrl", "http://" + Request.ServerVariables["HTTP_HOST"] + "/ViewTopic.aspx?topicId=" + topic.Id + "&messageId=" + message.Id + "#message_" + message.Id);

                MailSender mailSender = new MailSender(mailParser);
                mailSender.AddRecipient(bookmark.User.Email);
                mailSender.Send();
            }
        }
    }
}
